<script lang="tsx" setup>
import { TableColumn } from '@/types/table'
import { ElMessage, ElButton, ElMessageBox, ElImage, ElTag } from 'element-plus'
import * as CktApi from '@/api/creative/chuangkit'
import CktDesign from '@chuangkit/chuangkit-design'

const userFlag = '001'
let designEditor: any = null
const appId = '1cf71fc825044b6ea6858ce9bbd8b663'

/** 表格字段 */
const columns: TableColumn[] = [
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'imageUrl',
    label: '缩略图',
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      const url = cellValue
      return cellValue ? (
        <ElImage class="h-30" src={url} preview-src-list={[url]} fit="cover" preview-teleported />
      ) : (
        <span>暂无图片</span>
      )
    }
  },
  {
    field: 'templateTitle',
    label: '标题'
  },
  {
    field: 'kindName',
    label: '类别',
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      return <ElTag>{cellValue}</ElTag>
    }
  },
  {
    field: 'action',
    label: '操作',
    formatter: (row: Recordable, _: TableColumn, __: string) => {
      return (
        <div>
          <ElButton link type="primary" onClick={() => handleEdit(row)}>
            开始设计
          </ElButton>
          <ElButton link type="danger" onClick={() => handleDelete(row)}>
            移除
          </ElButton>
        </div>
      )
    }
  }
]

/** 列表相关方法 */
const {
  register: tableRegister,
  tableObject,
  tableMethods
} = useTable({
  getListApi: async (option: any) => {
    const { pageSize, pageNo, ...params } = option

    const newParams = Object.entries(params).reduce((prev, [key, value]) => {
      value && (prev[key] = value)
      return prev
    }, {})

    const list = await CktApi.getTemplateCollection({
      userFlag,
      pageSize,
      pageNo
      // kindId: 1
    })

    console.log(list)

    return {
      list: list,
      total: list.length
    }
  },
  delListApi: async (option) => {
    console.log('delete', option)
    await CktApi.deleteDesign({
      userFlag,
      designIds: option,
      terminal: 0
    })
    // 等待半秒再刷新
    await new Promise((resolve) => setTimeout(resolve, 500))
    return {}
  }
})
const { getList, setSearchParams } = tableMethods

// 用户编辑
// 用户点击编辑
const handleEdit = async (row: any) => {
  console.log(row)

  // 付费调起模板编辑器
  const payConfig = { charge_type: 2 }
  // 调用接口获取packageId
  const packageId = await CktApi.requestPackageId()

  // 如果能获取到付费id，则更改
  if (packageId) {
    payConfig.charge_type = 1
    payConfig['package_id'] = packageId
  }
  // 需要签名
  const needSign = {
    app_id: appId,
    // 用户id
    user_flag: userFlag,
    expire_time: Date.now() + 2 * 60 * 1000,
    device_type: 1,
    template_id: row.templateId,
    setting_code: 'RBGJ',
    ...payConfig,
    charging_template_limit: 2,
    coop_font_limit: 2,
    coop_material_limit: 2
  }
  // 获取sign接口
  const sign = await CktApi.getTemplateEditorSign(needSign)
  designEditor = new CktDesign({
    ...needSign,
    sign,
    show_name: '1',
    show_watermark: '1'
  })
  designEditor.open()
  // 设置文件名称，在pro-posters-editor中接收
  // ;(window as any).$emit('setSourceName', { fileName: row.designTitle })
}

// 取消收藏
const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定移除这个收藏吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await CktApi.templateCancelCollection({
    userFlag,
    templateId: row.templateId
  })
  ElMessage({
    message: '成功移除',
    type: 'success'
  })
  await getList()
}

onMounted(() => {
  getList()
  // 监听编辑器回调
  ;(window as any)['chuangkitComplete'] = () => {
    getList()
  }
})
</script>

<template>
  <!-- 搜索工作栏 -->
  <!-- <ContentWrap>
    <Search :schema="searchFields" @search="setSearchParams">
      <template #actionMore>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['train:course:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 添加
        </el-button>
      </template>
    </Search>
  </ContentWrap> -->

  <!-- 列表 -->
  <ContentWrap>
    <Table
      @register="tableRegister"
      :columns="columns"
      :data="tableObject.tableList"
      row-key="id"
      :loading="tableObject.loading"
      :pagination="{ total: tableObject.total }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
    />
  </ContentWrap>
</template>
